import 'package:flutter/material.dart';
import 'package:opensource_download/models/category.dart';

class CategorySidebar extends StatelessWidget {
  const CategorySidebar({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 200,
      color: Colors.grey[100],
      child: ListView.builder(
        itemCount: categories.length,
        itemBuilder: (context, index) {
          return CategoryItem(category: categories[index]);
        },
      ),
    );
  }
}

class CategoryItem extends StatefulWidget {
  final Category category;
  
  const CategoryItem({super.key, required this.category});

  @override
  State<CategoryItem> createState() => _CategoryItemState();
}

class _CategoryItemState extends State<CategoryItem> {
  final GlobalKey _key = GlobalKey();
  OverlayEntry? _overlayEntry;
  
  @override
  Widget build(BuildContext context) {
    return MouseRegion(
      onEnter: (_) => _showOverlay(),
      onExit: (_) => _hideOverlay(),
      child: Container(
        key: _key,
        padding: const EdgeInsets.all(16),
        child: Text(widget.category.name),
      ),
    );
  }

  void _showOverlay() {
    final RenderBox renderBox = _key.currentContext!.findRenderObject() as RenderBox;
    final position = renderBox.localToGlobal(Offset.zero);

    _overlayEntry = OverlayEntry(
      builder: (context) => Positioned(
        left: position.dx + renderBox.size.width,
        top: position.dy,
        child: MouseRegion(
          onExit: (_) => _hideOverlay(),
          child: Card(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: widget.category.subCategories?.map((subCategory) => 
                InkWell(
                  onTap: () => _onSubCategoryTap(subCategory),
                  child: Container(
                    padding: const EdgeInsets.all(8),
                    width: 150,
                    child: Text(subCategory.name),
                  ),
                ),
              ).toList() ?? [],
            ),
          ),
        ),
      ),
    );

    Overlay.of(context).insert(_overlayEntry!);
  }

  void _hideOverlay() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  void _onSubCategoryTap(SubCategory subCategory) {
    // TODO: 实现请求后台并更新软件列表的逻辑
    print('Selected subcategory: ${subCategory.name}');
    _hideOverlay();
  }
}



// 示例数据
final categories = [
  Category(
    name: '开发工具',
    id: 1,
    subCategories: [
      SubCategory(name: 'IDE', id: '1'),
      SubCategory(name: '编辑器', id: '2'), 
      SubCategory(name: '版本控制', id: '3'),
    ],
  ),
  Category(
    id: 2,
    name: '数据库',
    subCategories: [
      SubCategory(name: '关系型数据库', id: '4'),
      SubCategory(name: 'NoSQL', id: '5'),
      SubCategory(name: '图数据库', id: '6'),
    ],
  ),
  // 添加更多分类...
]; 